package com.springvision.core.tcpclient;

import java.util.concurrent.TimeUnit;

import com.jeeplus.common.utils.SpringContextHolder;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;

/**
 * @author qwh
 * @since 2017/6/23 13:58
 */
public class TcpClient {

	private Bootstrap bootstrap = SpringContextHolder.getApplicationContext().getBean("bootstrap", Bootstrap.class);

	protected Channel channel;

	public void connect() throws InterruptedException {
		System.err.println("-----start-----");
		// channel = bootstrap.connect("127.0.0.1", 8090).sync().channel();
		// System.out.println("-----end-------");
		ChannelFuture future = bootstrap.connect("127.0.0.1", 8400).addListener(new ChannelFutureListener() {

			public void operationComplete(ChannelFuture futureListener) throws Exception {
				if (futureListener.isSuccess()) {
					channel = futureListener.channel();
					System.err.println("Client:Connect To Server Successfully");
				} else {
					System.err.println("Client:Failed To Connect To Server,Try Again After 10s...");

					futureListener.channel().eventLoop().schedule(new Runnable() {

						@Override
						public void run() {
							try {
								connect();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}, 10, TimeUnit.SECONDS);// 短链接
				}
			}
		});
		channel = future.channel();
		System.out.println("-----end-------");
	}

	public Channel getChannel() {
		return channel;
	}

	public TcpClient() throws InterruptedException {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				try {
					connect();
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

		}).run();
	}
}
